package leetcode.code1234;

import leetcode.IDebug;
import leetcode.helper.H;

public class Solution implements IDebug {

	char[] d = new char[] { 'Q', 'W', 'E', 'R' };
	int[] hash = new int[128];

	public int balancedString(String s) {
		for (int i = 0; i < d.length; i++) {
			hash[d[i]] = i;
		}
		int[] cnts = new int[d.length];
		char[] cs = s.toCharArray();
		int len = cs.length;
		int need = len >> 2;
		for (int i = 0; i < cs.length; i++) {
			cnts[hash[cs[i]]]++;
		}
		int[] more = new int[d.length];
		int balance = 0;
		for (int i = 0; i < more.length; i++) {
			more[i] = Math.max(cnts[i] - need, 0);
			if (more[i] != 0) {
				balance |= (1 << i);
			}
		}
		if (balance == 0) {// 本来就平衡
			return 0;
		}
		int l = 0, r = 0;
		int ans = len;
		int[] win = new int[d.length];
		while (r < len) {
			while (r < len && balance != 0) {
				int index = hash[cs[r++]];
				win[index]++;
				if (more[index] != 0 && win[index] == more[index]) {
					balance ^= 1 << index;
				}
			}
			while (l < r && balance == 0) {
				int index = hash[cs[l++]];
				win[index]--;
				if (more[index] != 0 && more[index] - win[index] == 1) {
					balance ^= 1 << index;
				}
			}
			ans = Math.min(ans, r - l + 1);
		}
		return ans;
	}

	@Override
	public void debug4() {
		H.compare(1, this.balancedString("QQWE"));

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
